package cn.tedu._05weibo.commen.exception;

import cn.tedu._05weibo.commen.response.JsonResult;
import cn.tedu._05weibo.commen.response.StatusCode;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import javax.validation.ConstraintViolationException;

@RestControllerAdvice
@Slf4j
public class GlobalExceptionHandler {

    /**
     * ExceptionHandler  注解: 标识此方法为异常处理方法
     * 前提:控制器中抛出了异常
     * 1.首先查看是否定义全局异常处理器;
     * 2.已定义,则在类中定位处理该异常的异常处理方法;
     * 3.如果未定义,则定位该异常父类异常的异常处理方法;
     * 4.如果父类也未定义,则使用Spring MVC 默认的异常处理机制[不友好];
     * @param ex
     * @return
     */
    @ExceptionHandler
    public JsonResult doHandleIllegalArgumentException (IllegalArgumentException ex){
        log.error("ex = " + ex.getMessage());
        return new JsonResult(StatusCode.OPERATION_FAILED,ex.getMessage());
    }
//    @ExceptionHandler
//    public JsonResult doHandleRuntimeException(RuntimeException ex){
//        log.error("ex = " + ex.getMessage());
//        return new JsonResult(StatusCode.OPERATION_FAILED,ex.getMessage());
//    }

    /**
     * 1.能够处理所有控制器抛出的异常;
     * 2.开发过程中尽量不要加;
     * @param ex
     * @return
     */
/*    @ExceptionHandler
    public JsonResult doThrowableException(Throwable ex){
        log.error("ex = " + ex.getMessage());
        return new JsonResult(StatusCode.THROWABLE_ERROR,ex.getMessage());
    }*/

    @ExceptionHandler
    public JsonResult doHandleMethodArgumentNotValidException(MethodArgumentNotValidException ex){
        log.error("ex = " + ex.getFieldError().getDefaultMessage());
        return new JsonResult(StatusCode.VALIDATED_ERROR,ex.getFieldError().getDefaultMessage());
    }

    @ExceptionHandler
    public JsonResult doHandle(ConstraintViolationException ex){
        String message = ex.getMessage().split(":")[1].trim();
        log.error("ex = " + message);
        return new JsonResult(StatusCode.VALIDATED_ERROR, message);
    }
}
